import request from '../common/request';
let callback = null;
/**
 * 获取详情
 * @param {*} id 
 * @param {*} type 
 * @returns 
 */
function getDetailData(id, type) {
	return new Promise(resolve => {
		let url = '/meeting/detail'
		switch (type) {
			case 'specialhd':
				url = '/Specialhd/detail';
				break;
			case 'confer':
				url = '/confer/detail';
				break;
			case 'inspect':
				url = '/inspect/detail';
				break;
			case 'masses':
				url = '/Lxqz/detail';
				break;
			case 'hytz':
				url = '/Pxnotice/detail';
				break;
			case 'tasupervise':
				url = '/Learn/detail';
				break;
			case 'survey':
				url = '/survey/detail';
				break;
			default:
				url = '/meeting/detail'
		}
		request({
			url: url,
			data: {
				meet_id: id
			},
			method: 'POST'
		}).then(res => {
			if (res.code == 1) {
				resolve(res.data.address)
			} else {
				if (callback) {
					callback({
						status: false,
						msg: '获取会议地点失败'
					})
				} else {
					uni.showModal({
						content: '获取会议地点失败',
						showCancel: false,
					});
				}
				resolve('')
			}
		})
	})
}
/**
 * 地址解析 -- 获取会议地点经纬度
 * @param {*} address 
 * @returns 
 */
function getLatlng(address) {
	return new Promise(resolve => {
		uni.request({
			url: `https://restapi.amap.com/v3/geocode/geo?output=JSON&address=${address}&key=893316f5d167d7998cfaa9018d27c538`,
			data: {},
			success: function (res) {
				// console.log(res)
				if (res.data.status == 1) {
					let latlng = res.data.geocodes[0].location.split(",");
					let addressLatlng = {
						lat: Number(latlng[1]), //纬度
						lng: Number(latlng[0]) //经度
					}
					resolve(addressLatlng)
				} else {
					uni.showModal({
						content: res.data.info,
						showCancel: false,
					});
					resolve('')
				}
			},
			fail: function (err) {
				if (callback) {
					callback({
						status: false,
						msg: '会议地点解析调用失败'
					})
				} else {
					uni.showModal({
						content: '会议地点解析调用失败',
						showCancel: false,
					});
				}
				resolve('')
			}
		})
	})
}
/**
 * 获取用户当前位置信息
 * @returns 
 */
function getUserLocation() {
	return new Promise(resolve => {
		// 获取用户是否开启 授权获取当前的地理位置、速度的权限。
		uni.getSetting({
			success: (res) => {
				// 如果没有授权
				if (!res.authSetting['scope.userLocation']) {
					// 则拉起授权窗口
					uni.authorize({
						scope: 'scope.userLocation',
						success() {
							//点击允许后--就一直会进入成功授权的回调 就可以使用获取的方法了
							getLocation().then(data => resolve(data))
						},
						fail(error) {
							//点击了拒绝授权后--就一直会进入失败回调函数--此时就可以在这里重新拉起授权窗口
							console.log('拒绝授权', error)
							uni.showModal({
								title: '提示',
								content: '若点击不授权，将无法使用功能',
								cancelText: '不授权',
								cancelColor: '#999',
								confirmText: '授权',
								confirmColor: '#f94218',
								success(res) {
									console.log(res)
									if (res.confirm) {
										// 选择弹框内授权
										uni.openSetting({
											success(res) {
												console.log(res.authSetting)
											}
										})
									} else if (res.cancel) {
										// 选择弹框内 不授权
										console.log('用户点击不授权')
									}
								}
							})
						}
					})
				} else {
					// 有权限则直接获取
					getLocation().then(data => resolve(data))
				}
			}
		})

	})
}
/**
 * 获取位置信息
 * @returns 
 */
function getLocation() {
	return new Promise(resolve => {
		uni.getLocation({
			type: 'gcj02',
			success: (res) => {
				// console.log('当前位置的经度：' + res.longitude);
				// console.log('当前位置的纬度：' + res.latitude);
				let location = {
					lng: res.longitude,
					lat: res.latitude,
				}
				// console.log(location)
				// 调用逆解析，获取经纬度的地点描述
				uni.request({
					url: `https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=${location.lng},${location.lat}&key=893316f5d167d7998cfaa9018d27c538`,
					data: {},
					success: function (res) {
						// console.log(res)
						if (res.data.status == 1) {
							let regeocode = res.data.regeocode
							// 默认使用匹配地点信息
							location.address = regeocode.formatted_address
							// 没有，则拼接省市区等信息
							if (!location.address || location.address == '') {
								let addressComponent = regeocode.addressComponent
								location.address = addressComponent.province;
								if (!Array.isArray(addressComponent.city)) {
									location.address += addressComponent.city
								}
								if (!Array.isArray(addressComponent.district)) {
									location.address += addressComponent.district
								}
								if (!Array.isArray(addressComponent.township)) {
									location.address += addressComponent.township
								}
								if (!Array.isArray(addressComponent.streetNumber
									.street)) {
									location.address += addressComponent.streetNumber
										.street
								}

								if (!Array.isArray(addressComponent.streetNumber
									.number)) {
									location.address += addressComponent.streetNumber
										.number
								}
								if (!Array.isArray(addressComponent.building.name)) {
									location.address += addressComponent.building.name
								}
							}
							// console.log(location)
							resolve(location)
						} else {
							// 解析失败，提示失败原因
							location.info = res.data.info
							uni.showModal({
								content: res.data.info,
								showCancel: false,
							});
							resolve(location)
						}
					},
					fail: function (err) {
						if (callback) {
							callback({
								status: false,
								msg: '当前位置信息解析调用失败'
							})
						} else {
							uni.showModal({
								content: '当前位置信息解析调用失败',
								showCancel: false,
							});
						}
						resolve(location)
					}
				})
			},
			fail: (error) => {
				if (callback) {
					callback({
						status: false,
						msg: '获取位置失败'
					})
				} else {
					uni.showModal({
						content: '获取位置失败',
						showCancel: false,
					});
				}
				resolve('')
			}
		})
	})

}
/**
 * 计算两点的距离
 * @param {*} lat1 
 * @param {*} lon1 
 * @param {*} lat2 
 * @param {*} lon2 
 * @returns 
 */
function getDistance(lat1, lon1, lat2, lon2) {
	var radLat1 = (lat1 * Math.PI) / 180; //将角度换算为弧度
	var radLat2 = (lat2 * Math.PI) / 180; //将角度换算为弧度
	var a = radLat1 - radLat2;
	var b = (lon1 * Math.PI) / 180 - (lon2 * Math.PI) / 180;
	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math
		.sin(b / 2), 2)));
	s = s * 6378137.0; // 取WGS84标准参考椭球中的地球长半径(单位:m)
	//s = Math.round(s * 10000) / 10000; //两点之间距离(保留四位)
	return s; //(单位:m)
}
/**
 * 签到
 * @param {*} id 
 * @param {*} type 
 * @param {*} address 
 * @param {*} callback 
 * @returns 
 */
export default async function signIn(id, type, address, _callback) {
	callback = _callback
	// 判断会议地点，没有，则调用详情接口获取
	if (!address) address = await getDetailData(id, type)
	// 会议地点获取失败，进程终止
	if (!address) return false
	Promise.all([getUserLocation(), getLatlng(address)]).then(data => {
		let userLocation = data[0],
			addressLatlng = data[1];
		// 判断用户位置信息
		if (!userLocation || userLocation == '' || !userLocation.lat) {
			if (callback) {
				callback({
					status: false,
					msg: '获取用户信息失败'
				})
			}
			return false
		}
		// 判断会议地点经纬度
		if (!addressLatlng || addressLatlng == '' || !addressLatlng.lat) {
			if (callback) {
				callback({
					status: false,
					msg: '会议地点解析失败'
				})
			}
			return false
		}
		// 计算距离
		let distance = getDistance(userLocation.lat, userLocation.lng, addressLatlng.lat, addressLatlng.lng)
		if (!distance || distance > 500) {
			if (callback) {
				callback({
					status: false,
					msg: '超出签到范围，无法签到'
				})
			} else {
				uni.showModal({
					content: '超出签到范围，无法签到',
					showCancel: false,
				});
			}
			return false
		}
		let url = '/meeting/signIn',
			params = {
				meet_id: id,
				address: userLocation.address,
				codeType: type
			}
		if (type) {
			switch (type) {
				case 'specialhd':
					url = '/Specialhd/signIn';
					break;
				case 'confer':
					url = '/confer/signIn';
					break;
				case 'inspect':
					url = '/inspect/signIn';
					break;
				case 'masses':
					url = '/Lxqz/joinMake';
					break;
				case 'hytz':
					url = '/Pxnotice/signIn';
					break;
				case 'tasupervise':
					url = '/Learn/signIn';
					break;
				case 'survey':
					url = '/survey/joinMake';
					break;
				default:
					url = '/meeting/signIn'
			}
		}
		request({
			url: url,
			data: params,
			method: 'POST'
		}).then(res => {
			if (callback) {
				callback({
					status: res.code == 1 ? true : false,
					msg: res.msg
				})
			} else if (res.code == 1) {
				uni.showModal({
					content: '扫码签到成功',
					showCancel: false,
				});
			} else {
				if (res.msg == '操作失败') {
					uni.showModal({
						content: '扫码签到失败',
						showCancel: false,
					});
				} else {
					uni.showModal({
						content: res.msg,
						showCancel: false,
					});
				}

			}
		})
	})
}